/**
 * @file: 
 * @author: Lengxx
 * @date: 2024-06-18
 */
<template>
  <PanelTitle classnames="mb-6" title="基本资料" />
  <Spin :spinning="loading">
    <Form :model="formState" :labelCol="{ style: { width: '100px' } }" >
      <div class="flex">
        <div class="flex-1">
          <FormItem label="登录账号" name="username" >
            <Input v-model:value="formState.username" disabled />
          </FormItem>
          <FormItem label="昵称" name="nickname" >
            <Input v-model:value="formState.nickname" />
          </FormItem>
          <FormItem label="联系电话" name="phone" >
            <Input v-model:value="formState.phone" />
          </FormItem>
          <FormItem name="action">
            <Button class="ml-[100px]" type="primary" @click="onSubmit" :loading="loading">更新信息</Button>
          </FormItem>
        </div>
        <div class="flex-1 flex flex-col items-center justify-center">
          <Avatar 
          :size="120"
          class="bg-yellow-200 mb-6" 
          :src="formState.avatar" 
          />
  
          <Upload 
          class="flex items-center justify-center flex-col"
          accept=".png,.jpg,.jpeg,.gif,.bmp" 
          :beforeUpload="onBeforeUpload"
          :showUploadList="false"
          >
            <Button :icon="h(UploadOutlined)">更换头像</Button>
          </Upload>
        </div>
      </div>
    </Form>
  </Spin>
</template>

<script lang="ts" setup>
import { get } from 'lodash-es'
import { reactive, h } from 'vue'
import * as api from '@/api/user'
import { useRequest } from '@vben/hooks'
import { useMessage } from '@/hooks/web/useMessage'
import { UploadOutlined } from '@ant-design/icons-vue'
import { Form, FormItem, Input, Avatar, Button, Upload, Spin } from 'ant-design-vue'
import { PanelTitle } from '@/components/PanelTitle'
import { useUserStore } from '@/store/modules/user'

const { loading, runAsync: updateUserInfo } = useRequest(api.updateUserInfo, { manual: true })
const { createMessage } = useMessage();
const { userInfo } = useUserStore();
const userState = get(userInfo, 'user', {}) as Recordable;

const formState = reactive({
  username: '',
  nickname: '',
  phone: '',
  avatar: '',
  id: '',
  ...userState
})

async function onSubmit() {
  console.log('保存', formState)
  const data: api.IUserInfo = {
    id: formState.id,
    nickname: formState.nickname,
    phone: formState.phone,
    avatar: formState.avatar
  };
  await updateUserInfo(data);
  createMessage.success('更新成功');
}

/** 头像上传 */
function onBeforeUpload(file) {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    formState.avatar = reader.result as string
  }
  return false
}

</script>
